package com.lighting.shortlink.project.service.impl;

import com.lighting.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * URL 标题接口实现层
 * @author : lighting
 */
@Service
public class UrlTitleServiceImpl implements UrlTitleService {
    @SneakyThrows
    @Override
//    获取给定 URL 的页面标题
    public String getTitleByUrl(String url) {
        URL targetUrl = new URL(url);
//        HttpURLConnection 是 URLConnection 的具体实现类
//        打开链接
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");//设置连接欸对 请求方法 为 get
        connection.connect();//连接到 URL
        int responseCode = connection.getResponseCode();//获取连接的响应码
        if (responseCode == HttpURLConnection.HTTP_OK)//连接成功
        {
            // 使用 Jsoup 连接给定的 URL，并获取页面的 Document 对象
            Document document = Jsoup.connect(url).get();
            return document.title(); // 返回页面标题
        }
        return "err while fetching title."; // 如果获取失败，则返回错误信息
    }
}
